package sv.gob.mh.dgii.ssc.controller.configuration;

import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import sv.gob.mh.dgii.security.SscUserDetailsImpl;

@Controller
public class HomeController {

    private final static Log log = LogFactory.getLog(HomeController.class);

    @RequestMapping(value = "/")
    public String index(Model model) {
        return "redirect:/home";
    }

    @RequestMapping(value = "/home")
    public String home(Model model, HttpServletRequest request) {
        // TODO: NO MODIFICAR LA SIGUIENTE LINEA, SE ALMACENA EN 'SESSIONSCOPE' EL NOMBRE DE USUARIO
        request.getSession().setAttribute("sessionUserName", getUsuario());
        //...
        return "home";
    }

    public SscUserDetailsImpl getPrincipal() {
        return (SscUserDetailsImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    public String getUsuario() {
        String user = "USER";
        try {
            SscUserDetailsImpl principals = getPrincipal();
            user = principals.getUsuario();
        } catch (Exception e) {
            log.debug("Error while trying to session username.", e);
        }
        return user;
    }
}
